/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include <fstream>
#include "log/Log.h"
#include "PluginUtilities.h"
#include "CertManager.h"

using namespace OBSPlugin;

namespace {
    constexpr auto MODULE = "CertMgr";
    const std::string CRET_NAME = "certification.pem";
    const std::string DEFUALT_ROOT_PATH = "/opt/logpath";
    constexpr uint32_t MAX_RETRY_TIMES = 3;
}

CertManager::CertManager(const std::string &rootPath, const std::string& jobId)
{
    this->m_rootPath = rootPath;
    this->m_jobId = jobId;
}

CertManager::CertManager(const std::string& jobId)
{
    this->m_rootPath = DEFUALT_ROOT_PATH;
    this->m_jobId = jobId;
}

bool CertManager::SaveFile(const std::string &content)
{
    if (content.empty()) {
        return true;
    }
    std::string certPath = m_rootPath + "/ca_" + m_jobId;
    if (IsDirExist(certPath)) {
        HCP_Log(INFO, MODULE) << "The certification already exists." << HCPENDLOG;
        return true;
    }
    if (!OBSPlugin::RecurseCreateDirectory(certPath)) {
        HCP_Log(ERR, MODULE) << "Failed to create temp CA path" << HCPENDLOG;
        return false;
    }
    HCP_Log(DEBUG, MODULE) << "Start to save cert" << HCPENDLOG;
    std::string filePath = m_rootPath + "/ca_" + m_jobId + "/" + CRET_NAME;
    std::vector<std::string> fileContent {};
    fileContent.push_back(content);
    if (!WriteFile(filePath, fileContent)) {
        HCP_Log(ERR, MODULE) << "Save file failed, filename: " << filePath << HCPENDLOG;
        return false;
    }
    return true;
}

bool CertManager::RemoveCertFile()
{
    std::string certPath = m_rootPath + "/ca_" + m_jobId;
    if (OBSPlugin::Remove(certPath)) {
        HCP_Log(DEBUG, MODULE) << "Remove Certification success" << HCPENDLOG;
        return true;
    }
    HCP_Log(ERR, MODULE) << "Remove Certification failed" << HCPENDLOG;
    return false;
}

std::string CertManager::GetCAPath()
{
    std::string cafile = GetCAFile();
    if (!cafile.empty()) {
        return GetPathName(cafile);
    }
    return "";
}

std::string CertManager::GetCAFile()
{
    std::string cafile = m_rootPath + "/ca_" + m_jobId + "/" + CRET_NAME;
    if (IsFileExist(cafile)) {
        return cafile;
    }
    return "";
}